import React, { useState, useEffect } from 'react';
import {
  PermissionsAndroid,
  StyleSheet,
  TouchableOpacity,
  Image,
  View,
} from 'react-native';
import DocumentPicker from 'react-native-document-picker';
import FileViewer from 'react-native-file-viewer';
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
import { Toast, Modal, ImagePicker } from '@ant-design/react-native';
import UserStore from '@/stores/userStore';
import { isAndroid, appId } from '@/constants';
import ApiClient from '@/services/apiClient';
import ClosableTag from './closableTag';
import { IconX } from './iconx';

const styles = StyleSheet.create({
  container: {
    flexWrap: 'wrap',
    flexDirection: 'row',
    alignItems: 'center',
  },
  fileItem: {
    justifyContent: 'center',
    alignItems: 'center',
    padding: 2,
  },
  filetext: {
    padding: 5,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#1284d6',
  },
  item: {
    marginRight: 5,
    marginBottom: 6,
    overflow: 'hidden',
  },
  closeWrap: {
    width: 16,
    height: 16,
    backgroundColor: '#999',
    borderRadius: 8,
    position: 'absolute',
    top: 4,
    right: 4,
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'hidden',
  },
  closeText: {
    color: '#ffffff',
    backgroundColor: 'transparent',
    fontSize: 20,
    height: 20,
    marginTop: -8,
    fontWeight: '300',
  },
  image: {
    width: 80,
    height: 80,
    overflow: 'hidden',
    borderRadius: 5,
  },
});
export default function PhotoCameraPicker({
  photos, // ['',''] => [{ uri name type}]
  disabled,
  onFileChange,
  multiple,
  usePicker = false,
}) {
  const [files, setFiles] = useState([
    /*{ name: 'file', uri: '' }*/
  ]); // [{ uri, name, type(image/jpeg) }]
  const userStore = UserStore.useStore();
  const [androidGranted, setAndroidGranted] = useState(true);
  useEffect(() => {
    if (isAndroid) {
      requestPhotoPermission();
    }
    if (photos) {
      setFiles(
        photos.map((ph) => ({
          uri: ph,
          //uri: 'http://fileservice.loongair.cn/ph',
          name: `${new Date().getTime()}.jpeg`,
          type: 'image/jpeg',
        })),
      );
    }
  }, []);

  const requestPhotoPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.CAMERA,
        {
          title: '需要访问相册',
          message: '需要访问相册',
        },
      );
      setAndroidGranted(granted !== PermissionsAndroid.RESULTS.DENIED);
    } catch (err) {
      console.warn('request permission', err);
    }
  };
  const handleFileView = async (file) => {
    try {
      await FileViewer.open(file.uri, { showOpenWithDialog: true });
    } catch (err) {
      console.log(err);
    }
  };
  /**
   * 上传文件服务器
   *
   * @param {*} fileItems  [{ uri | data, type, name, }]
   */
  const postToFileServer = async (fileItems) => {
    const toasting = Toast.loading('文件上传中');
    try {
      const formData = new FormData();
      const fields = {
        AppId: appId,
        PlateId: 'Plate',
        UserId: userStore.user.UserId,
        KeyWords: '',
        FileDesc: '',
      };
      Object.keys(fields).forEach((key) => {
        formData.append(key, fields[key]);
      });
      for (let i = 0; i < fileItems.length; i += 1) {
        const mimeTypes = fileItems[i].type.split('/');
        formData.append('filedata', {
          uri: fileItems[i].uri,
          type: fileItems[i].type, // android without this network error
          name: `${new Date().getTime()}.${mimeTypes[mimeTypes.length - 1]}`,
        });
      }
      const uploadRes = await ApiClient.post(
        'http://fileservice.loongair.cn/FileHandler/FileUploadHandler2.aspx',
        formData,
      );
      // console.log(uploadRes);
      if (onFileChange) {
        onFileChange(uploadRes.data); // FilePath FileName
      }
      setFiles(files.concat(fileItems));
    } catch (err) {
      Modal.alert('上传文件失败', err.message);
    }
    Toast.remove(toasting);
  };
  const showDocumentPicker = async () => {
    try {
      let results;
      if (multiple) {
        results = await DocumentPicker.pickMultiple();
      } else {
        const result = await DocumentPicker.pick();
        results = [result];
      }
      await postToFileServer(results);
    } catch (err) {
      if (DocumentPicker.isCancel(err)) {
        // User cancelled the picker, exit any dialogs or menus and move on
      } else {
        Modal.alert('获取文件失败', err.message);
      }
    }
  };
  const showPicker = async () => {
    launchImageLibrary(
      {
        mediaType: 'photo',
        includeBase64: false,
        //maxHeight: 200,
        //maxWidth: 200,
      },
      async (response) => {
        if (!response.didCancel) {
          const file = {
            uri: response.uri,
            type: response.type,
          };
          await postToFileServer([file]);
        }
      },
    );
  };
  const handleTakeImage = () => {
    launchCamera(
      {
        mediaType: 'photo',
        includeBase64: false,
        //maxHeight: 200,
        //maxWidth: 200,
      },
      async (response) => {
        if (!response.didCancel) {
          const file = {
            uri: response.uri,
            type: response.type,
          };
          await postToFileServer([file]);
        }
      },
    );
  };
  const handleFileRemove = (file) => {
    setFiles(files.filter((fl) => fl.uri !== file.uri));
    // onFileRemove
  };
  return (
    <>
      <View style={styles.container}>
        {files.map((file) => (
          <View style={[styles.fileItem]} key={file.uri}>
            <ClosableTag
              onClose={() => handleFileRemove(file)}
              onPress={() => handleFileView(file)}
              showClose={!disabled}
            >
              {file.type.indexOf('image') !== -1 ? (
                <Image source={{ uri: file.uri }} style={styles.image} />
              ) : (
                file.name
              )}
            </ClosableTag>
          </View>
        ))}
        {!disabled && (
          <TouchableOpacity onPress={handleTakeImage}>
            <IconX origin="ant" name="camera" color="#1284d6" />
          </TouchableOpacity>
        )}
        {!disabled && usePicker && (
          <TouchableOpacity onPress={showPicker} style={{ marginLeft: 20 }}>
            <IconX origin="OCTICONS" name="file-media" color="#1284d6" />
          </TouchableOpacity>
        )}
      </View>
    </>
  );
}

// https://github.com/Elyx0/react-native-document-picker/issues/167
